--量产测试
import("System")
import("System.IO.Ports")
import("Jodell.Tool","Jodell.Tool")

function intToBinStr(x)
    local t = {}
    while x > 0 do
        local rest = x % 2
        table.insert(t, 1, rest) -- 在表的开头插入余数
        x = math.floor(x / 2)
    end
    if #t == 0 then t[1] = 0 end -- 如果数字是0，则直接返回0
    return table.concat(t)
end

-- 连接夹爪
client=Lua_ModbusRtuClient()
client.PortName="COM8"
client:Connect()

-- 切换串口模式
client:WriteUInt16(1, 1024,  1)	

Delay(50)

-- 启用产品测试模式
client:WriteUInt16(1, 1003,  1)	

-- 往复运动10次
Info("---往复运动测试---")
for i = 0, 19 do
	if (IsCancel) then
		break
	end
	client:WriteUInt16(1, 1018 + i % 2,  1)	
    if (i % 2 == 0) then
        Info(string.format("\t打开%d" , i // 2 + 1))
    else
        Info(string.format("\t闭合%d" , i // 2 + 1))
    end
	Delay(400)
end

-- 数字输出跑马灯
Info("--数字输出跑马灯---")
for i = 0, 8 do
    if (IsCancel) then
		break
	end
    local value = 1 << (i % 3)
    local ret = client:WriteUInt16(1, 1007, value)
    Info(string.format("\t输出信号%d, %s", ret, intToBinStr(value)))
    Delay(500)	
end


-- 数字输入<-->输出映射
Info("--数字输入<-->输出映射---")
local input_value = 0xFFFF
for i = 0, 10000 do
    if (IsCancel) then
		break
	end
    local ret, value = client:ReadUInt16(1, 2001)
    if (input_value ~= value) then
        input_value = value
        Info(string.format("\t输入信号%d, %s" , ret, intToBinStr(input_value)))
        Delay(50)
        client:WriteUInt16(1, 1007,  input_value)
    end
    Delay(50)	
end

-- 切换IO模式
client:WriteUInt16(1, 1024,  0)	

Delay(50)

-- 禁用产品测试模式
client:WriteUInt16(1, 1003,  0)	

client:Disconnect()
